#include "SymbolTable.h"
#include "Language.h"
#include <string>
#include <iostream>
using namespace std;

Symbol::Symbol(int address, Record record)
{
	this->address = address;
	this->record = record;
}

Symbol::Symbol()
{
}

SymbolTable::SymbolTable()
{
	memoryAddress = 3000;
	location = 0;
}

int SymbolTable::GetAddress(const Record & record) const
{
	// Find the record in symbol table
	for(int i = 0; i < location; i++)
	{
		if(table[i].record == record)
			return table[i].address;
	}
	// return error
	return -1;	
}

void SymbolTable::Insert(const Record & record)
{
	// Create the new symbol
	Symbol newSymbol(memoryAddress, record);
	// Add to table
	table.push_back(newSymbol);
	// Out to console
	cout<<"Inserting Symbol:\t"<<"Lexeme: "<< newSymbol.record.Lexeme()<<"Address: "<<newSymbol.address<<"Identifier: "<< ConvertIdentifier(newSymbol.record.GetIdentifier())<< endl;
	location++;
	memoryAddress++;
}

void SymbolTable::Print(const string& fileName)
{
    ofstream outFile;
	outFile.open(fileName, ofstream::out| ofstream::app);
    if(outFile.is_open())
    {
		outFile<< "-------Symbol Table--------\n\n"<<endl;
		outFile<< "Identifier"<<"\t"<< "Memory Location" <<"\t"<< "Type"<< endl;
		for(int i = 0 ; i < location; i++)
		{
			outFile << table[i].record.Lexeme()<<"\t\t"<<table[i].address<<"\t\t\t"<< ConvertIdentifier(table[i].record.GetIdentifier() )<< endl;
		}
    }
    outFile.close();

}

Record SymbolTable::GetRecord(const Record & record) const
{
	for(int i = 0; i < location; i++)
	{
		if(table[i].record == record)
			return table[i].record;
	}
}